package com.yu.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.math3.util.Pair;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.stonehenge.backend.tools.ConnU;
import com.stonehenge.backend.tools.StaticToolit;

/** 
 * @author fulingjin E-mail: fulingjin@gmail.com
 * @version 1.0 Date：2016年7月31日 下午4:08:43 
 * Comment：
 */
public class QQIMComponent {
	private static final int TIMEOUT_2000 = 2000;
	private static final int TIMEOUT_10000 = 10000;

    private static final Logger logger = LoggerFactory.getLogger(QQIMComponent.class);

	public final static long skdAppid = 1400012825L;
	public final static String identifier ="admin";
	public final static String privStr = 
		    "-----BEGIN PRIVATE KEY-----\n" +
			"MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgy5tgnZjzWe2scfP4t4Zs\n"+
			"PdTPo4miSnRLe8u7UEaeH0ahRANCAAREpKNJ+F0HV05PDUWGJWle0FbC1uDwP37/\n" +
			"SYpcwiEvJ3yJltLn0Or3dQZ29Ic15jeQ9L4KydQ2tpiOzDA0dyH5\n"
			+ "-----END PRIVATE KEY-----\n";		    
	public final static String pubStr = "-----BEGIN PUBLIC KEY-----\n"+
			"MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAERKSjSfhdB1dOTw1FhiVpXtBWwtbg8D9+\n" + 
			"/0mKXMIhLyd8iZbS59Dq93UGdvSHNeY3kPS+CsnUNraYjswwNHch+Q==\n" +
			"-----END PUBLIC KEY-----\n";
	
	public static final String QQIM_PREFIX = "ucar";
	public static final String QQIM_Domain_GroupId = "GroupId";    
	public static final String QQIM_Domain_GroupIdList = "GroupIdList";    
	public static Pair<String, Long> adminSig;
	private Random rn = new Random();

	private static final String apiUrl="https://console.tim.qq.com";
	private static final String URL_USERCREATE = apiUrl + "/v4/im_open_login_svc/account_import";
	private static final String URL_USERPROFILEUPDATE = apiUrl + "/v4/profile/portrait_set";

	private static final String URL_GROUPCREATE = apiUrl + "/v4/group_open_http_svc/create_group";
    private static final String URL_GROUP_ADD_MEMBER = apiUrl + "/v4/group_open_http_svc/add_group_member";
    private static final String URL_GROUP_DEL_MEMBER = apiUrl + "/v4/group_open_http_svc/delete_group_member";
    private static final String URL_GROUP_DISMISS = apiUrl + "/v4/group_open_http_svc/destroy_group";

	private static final String URL_USERGROUP_QUERY = apiUrl + "/v4/group_open_http_svc/get_joined_group_list";
	private static final String URL_GROUPUPDATE = apiUrl + "/v4/group_open_http_svc/modify_group_base_info";
	private static final String URL_GROUP_QUERY= apiUrl + "/v4/group_open_http_svc/get_group_info";
    private static final String URL_GROUP_MEMBER_QUERY= apiUrl + "/v4/group_open_http_svc/get_group_member_info";
	private static final String URL_IM_SENDMSG= apiUrl + "/v4/openim/sendmsg";
	private static final String URL_IM_SENDMSG_BATCH= apiUrl + "/v4/openim/batchsendmsg";
	private static final String URL_GROUP_LIST= apiUrl + "/v4/group_open_http_svc/get_appid_group_list";
	private static final String URL_IM_SENDGROUPMSG= apiUrl + "/v4/group_open_http_svc/send_group_msg";
    private static final String URL_IM_SEND_GROUP_SYSTEMMSG= apiUrl + "/v4/group_open_http_svc/send_group_system_notification";
    
    private static final String URL_CHANGE_GROUP= apiUrl + "/v4/group_open_http_svc/change_group_owner";
	

	public String checkPrefix(String str){
		if(str==null)
			return null;
		if(str.startsWith(QQIM_PREFIX))
			return str;
		return QQIM_PREFIX+str;
	}
    
	private String getAdminSig(){
		long st=System.currentTimeMillis();
		if(adminSig!=null && st - adminSig.getSecond()< 180*24*3600*1000L)
			return adminSig.getFirst();
		 //String sig=getSig(identifier);
		 String sig = null;
		 if(sig==null){
			 logger.error("sig null!!!!");
			 return null;
		 }
		 adminSig = new Pair<String, Long>(sig,st);
		 return adminSig.getFirst();
	}
	
    
	private List<NameValuePair> getUrlparams() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("usersig", "eJxFkFFPgzAQgP8LrzPadlSYb6SyiWyo0U3xpWnWA68KVFbn0PjfRTLi6-flct-dt-ewvD9V1qKWyslpq70Lj3gnA4aDxRakKhy0Paacc0bIaPfQ7rCpe8EI5ZRNCfmXqKF2WOAwqHSF9VHssOzJKs5FcifQPM-LxQREFm9smK3N27v4utJNKqKu89c3C5fzSSIuxapMXqJbFs2XYCHIZ-iZmeqcmNRdE22NT1NgZ4WfQvJY7fVTPC7Tr3K47a-e7*soCxk-SocVDDxklAbBbExX223zUTvpOgvDM35*AV2yVw0_"));
        params.add(new BasicNameValuePair("identifier", identifier));
        params.add(new BasicNameValuePair("sdkappid", String.valueOf(skdAppid)));
        params.add(new BasicNameValuePair("random", String.valueOf(rn.nextInt(90000)+10000)));
        params.add(new BasicNameValuePair("contenttype", "json"));
		return params;
	}
	
	public String sendMsgToClub(Map<String,Object> map,long clubid)  {
		String club=String.valueOf(clubid);
		club = checkPrefix(club);
		if(club==null) return null;
		
		List<NameValuePair> params = getUrlparams();
		Map<String, Object> json = Maps.newHashMap();
		json.put("GroupId", club); 
		//json.put("From_Account", "ucar"+10072745653068L); 
		json.put("Random", rn.nextInt(8912345)+1000000); 
		
        Map<String, Object> MsgBodyMap = Maps.newHashMap();
        MsgBodyMap.put("MsgType", "TIMCustomElem");
        MsgBodyMap.put("MsgContent", map);		
		json.put("MsgBody", Arrays.asList(MsgBodyMap)); 
		
		//UTF-8编码,解决中文问题
		String res = null;
		try{
			res=ConnU.postBody(URL_IM_SENDGROUPMSG, params, JSON.toJSONString(json), TIMEOUT_10000);
		}catch(Exception e){
			logger.error("sending to qq error",e);
			res = null;
		}
		return res;
	}
	
	 /*
     * 管理员发个人
     */
    public String sendMsg(Map content,long userid)  {
    	String id=String.valueOf(userid);
    	id = checkPrefix(id);
    	if(id==null) return null;
    	
        List<NameValuePair> params = getUrlparams();
        Map<String, Object> json = Maps.newHashMap();
        json.put("To_Account", String.valueOf(id)); //
        json.put("MsgRandom", rn.nextInt(Integer.MAX_VALUE)); //
        json.put("MsgTimeStamp", System.currentTimeMillis()/1000); //
        
        Map<String, Object> MsgBodyMap = Maps.newHashMap();

        MsgBodyMap.put("MsgContent", content);
        MsgBodyMap.put("MsgType", "TIMCustomElem");

        json.put("MsgBody", Arrays.asList(MsgBodyMap)); //

        //UTF-8编码,解决中文问题
        String res = null;
        try{
             res=ConnU.postBody(URL_IM_SENDMSG, params, JSON.toJSONString(json), TIMEOUT_10000);
        }catch(Exception e){
        	logger.error("sending to qq error",e);
        	
        	res = null;
        }
        return res;
    }
    
    /*
     * 管理员发个人
     */
    public String sendExpressMsg(String text,Map OfflinePushInfo,long userid)  {
    	String id=String.valueOf(userid);
    	id = checkPrefix(id);
    	if(id==null) return null;
    	
        List<NameValuePair> params = getUrlparams();
        Map<String, Object> json = Maps.newHashMap();
        
        json.put("SyncOtherMachine", 2);
        json.put("To_Account", String.valueOf(id)); //
        json.put("MsgRandom", rn.nextInt(Integer.MAX_VALUE)); //
        json.put("MsgTimeStamp", System.currentTimeMillis()/1000); //
        
        Map<String, Object> MsgBodyMap = Maps.newHashMap();

        Map<String,Object> textmap = Maps.newHashMap();
        textmap.put("Text", text);
        MsgBodyMap.put("MsgContent", textmap);
        MsgBodyMap.put("MsgType", "TIMCustomElem");

        json.put("MsgBody", Arrays.asList(MsgBodyMap)); //

        json.put("OfflinePushInfo", OfflinePushInfo);
        //UTF-8编码,解决中文问题
        String res = null;
        System.out.println(JSON.toJSONString(json));
        try{
             res=ConnU.postBody(URL_IM_SENDMSG, params, JSON.toJSONString(json), TIMEOUT_10000);
        }catch(Exception e){
        	logger.error("sending to qq error",e);
        	
        	res = null;
        }
        return res;
    }
    
    /*
     * 个人 发个人
     */
    public String sendMsg(String Text,String from ,String to) {
    	String fromid = checkPrefix(from);
    	if(fromid==null) return null;
    	
    	String toid = checkPrefix(to);
    	if(toid==null) return null;
    	
        List<NameValuePair> params = getUrlparams();
        Map<String, Object> json = Maps.newHashMap();
        json.put("SyncOtherMachine", 1);    // 将消息同时发送到from
        json.put("From_Account", String.valueOf(fromid)); //
        json.put("To_Account", String.valueOf(toid)); //
        json.put("MsgRandom", rn.nextInt(Integer.MAX_VALUE)); //
        json.put("MsgTimeStamp", System.currentTimeMillis()/1000); //
        Map<String, Object> MsgBodyMap = Maps.newHashMap();
        
        Map<String, Object> TextMap = Maps.newHashMap();
        TextMap.put("Text",Text);

        MsgBodyMap.put("MsgContent", TextMap);
        MsgBodyMap.put("MsgType", "TIMTextElem");

        json.put("MsgBody", Arrays.asList(MsgBodyMap)); //
        //UTF-8编码,解决中文问题
        String res = null;
        try{
             res=ConnU.postBody(URL_IM_SENDMSG, params, JSON.toJSONString(json), TIMEOUT_10000);
        }catch(Exception e){
        	logger.error("sending to qq error",e);
        	
        	res = null;
        }
        return res;
    }
    
    //=================================================
    //=================================================
    //=================================================
    //=================================================
    
    public String createUser(String id, String name)  {
    	id = checkPrefix(id);
    	if(id==null) return null;
    	
        List<NameValuePair> params = getUrlparams();
        Map<String, Object> json = Maps.newHashMap();
        json.put("Identifier", String.valueOf(id)); //
        json.put("Nick", name);

        //UTF-8编码,解决中文问题
        String res = null;
        try{
             res=ConnU.postBody(URL_USERCREATE, params, JSON.toJSONString(json), TIMEOUT_2000);
        }catch(Exception e){
        	
        	res = null;
        }
        return res;
    }
    
    public int isOKResponseCode0(String rescode) {

        if (rescode == null)
            return -1;
        JSONObject obj = JSON.parseObject(rescode);
        if (obj == null) {
            return -2;
        }
        String ok = obj.getString("ActionStatus");
        if ("OK".equals(ok))
            return 0;
        else {
            String errorCode = obj.getString("ErrorCode");
            if (errorCode != null && StaticToolit.isNumeric(errorCode))
                return Integer.valueOf(errorCode);
            else
                return -3;
        }
    }

    public String addGroupMembers(String groupid, List<String> userids)  {
        ArrayList<String> quserids = new ArrayList<String>();
        for (String userid : userids) {
            userid = checkPrefix(userid);
            if (null != userid)
                quserids.add(userid);
        }
        if(quserids.size()==0)
            return "userids err";

        groupid = checkPrefix(groupid);
        if(groupid==null)
            return "groupid err";

    	/*
{
    "GroupId": "@TGS#2J4SZEAEL",   // 要操作的群组（必填）
    "Silence": 0,   // 是否静默加人（选填）
    "MemberList": [  // 一次最多添加500个成员
    {
        "Member_Account": "tommy"  // 要添加的群成员ID（必填）
    },
    {
        "Member_Account": "jared"
    }]
}
    	 */

        List<NameValuePair> params = getUrlparams();

        Map<String, Object> json = Maps.newHashMap();
        json.put("GroupId", groupid);
        json.put("Silence", 0);

        ArrayList<Map<String, String>> memberlist = new ArrayList<Map<String, String>>();
        for (String quserid : quserids) {
            Map<String, String> oneUser = new HashMap<String, String>();
            oneUser.put("Member_Account", quserid);
            memberlist.add(oneUser);
        }
        json.put("MemberList", memberlist);

        String res = null;
        try{
            res=ConnU.postBody(URL_GROUP_ADD_MEMBER, params, JSON.toJSONString(json), TIMEOUT_2000);
        }catch(Exception e){
            logger.error("qq im error:",e);
            res = null;
        }
        return res;
    }
    
    
    public String changeGroupOwer(String groupid, String userid)  {
    	userid = checkPrefix(userid);
    	if(userid==null)
            return "userid err";
    	
        groupid = checkPrefix(groupid);
        if(groupid==null)
            return "groupid err";


        List<NameValuePair> params = getUrlparams();

        Map<String, Object> json = Maps.newHashMap();
        json.put("GroupId", groupid);
        json.put("NewOwner_Account", userid);

        String res = null;
        try{
            res=ConnU.postBody(URL_CHANGE_GROUP, params, JSON.toJSONString(json), TIMEOUT_2000);
        }catch(Exception e){
            logger.error("qq im error:",e);
            res = null;
        }
        return res;
    }
    
	public static void main(String[] args) {
		Map<String,Object> obj = Maps.newHashMap();
		Map<String,Object> data = Maps.newHashMap();
		data.put("type", 4);
		data.put("subtype", 302);
		Map<String,Object> info = Maps.newHashMap();
		info.put("redid",111);
		info.put("comment", "恭喜发财");
		
		data.put("info", info);
		obj.put("Data", JSONObject.toJSONString(data));
		obj.put("Desc", "新红包");
		QQIMComponent oneComponent = new QQIMComponent();
		System.out.println(JSONObject.toJSON(obj));
		System.out.println(oneComponent.sendMsgToClub(obj, 10002L));
	}


}
